package tech.lingrui.mnpanonymousservice.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json工具类
 *
 * @author lqs2
 * @date 2018/11/25, Sun
 */
public class JsonUtils {


    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    /**
     * 将对象转化为json字符串
     *
     * @param o 需要转换的对象
     * @return json字符串
     **/
    public static String convertToJsonStr(Object o) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(o);
    }


    /**
     * json 转JavaBean
     *
     * @param jsonStr json字符串
     * @param clazz   bean class
     * @return bean对象
     **/
    public static <T> T jsonToBean(String jsonStr, Class<T> clazz) throws Exception {
        OBJECT_MAPPER.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return OBJECT_MAPPER.readValue(jsonStr, clazz);
    }

}
